var dbUtil = require('../util/dbUtil');
var authUtil = require('../util/authUtil');
var mysqlUtil = require('../util/mysqlUtil');
var EventProxy = require('eventproxy');

/**
 * 查询
 */
var query = function(req, res) {
    var sql = "select * from t_upgrade_project p where " + authUtil.buildWorkGroupCondition(req);

    var searchVal = req.body.searchVal;
    if (searchVal != null && searchVal != '') {
        sql += " and (p.code like '%" + searchVal + "%' or p.name like '%" + searchVal + "%')";
    }
    if (req.body.enabled != null && req.body.enabled != '') {
        sql += " and p.enabled=" + req.body.enabled;
    }
    sql += " order by p.code";

    dbUtil.partitionQuery(sql, req, res);
};

/**
 * 修改
 */
var edit = function(req, res) {
    var id = req.query.id || '';

    var proxy = new EventProxy();
    proxy.all('getData', function(data) {
        var obj = data.length > 0 ? data[0] : {};
        res.render('upgradeProject/edit', obj);
    });

    mysqlUtil.exec('select * from t_upgrade_project where id=?', [id], function(err, result) {
        proxy.emit('getData', result);
    });
};

/**
 * 保存
 */
var save = function(req, res) {
    dbUtil.save('t_upgrade_project', 'upgradeProject', req, function(err, result) {
        var obj = {
            success: err == null
        };

        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(obj));
    });
};

/**
 * 删除
 */
var remove = function(req, res) {
    var id = req.body.id || '';
    var proxy = new EventProxy();
    var obj = { success: false };

    proxy.all('getUpgradePackageCount', function(data) {
        console.log(data);
        if (data.length.c > 0) {
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify(obj));
        } else {
            mysqlUtil.exec('delete from t_upgrade_project where id=?', [id], function(err, result) {
                obj.success = err == null;
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify(obj));
            });
        }
    });

    mysqlUtil.exec('select count(*) as c from t_upgrade_package where upgrade_project_id=?', [id], function(err, result) {
        proxy.emit('getUpgradePackageCount', result);
    });
};

exports.query = query;
exports.edit = edit;
exports.save = save;
exports.remove = remove;
